<template>
  <div class="wf-login">
    <div class="wf-login-text">登录</div>
    <div class="wf-login-from">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
      >
        <el-form-item prop="username">
          <el-input
            v-model.number="ruleForm.username"
            autocomplete="off"
            placeholder="用户名"
            @change="inputName(ruleForm.username)"
          ></el-input>
        </el-form-item>
        <el-form-item prop="userpass">
          <el-input
            type="password"
            v-model="ruleForm.userpass"
            autocomplete="off"
            placeholder="密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input
            class="wf-phone"
            v-model.number="ruleForm.phone"
            autocomplete="off"
            placeholder="手机号"
          >
          </el-input>
          <el-button
            class="wf-obtain"
            type="success"
            :disabled="isTelBtn"
            v-show="isObtain"
            @click="getVerificatCode"
            >获取验证码</el-button
          >
          <el-button
            class="wf-obtain"
            type="success"
            v-show="!isObtain"
            :disabled="isTelBtn"
            @click="getVerificatCode"
            >{{ timeLeft }}S 后再获取</el-button
          >
        </el-form-item>
        <el-form-item prop="message">
          <el-input
            v-model.number="ruleForm.message"
            autocomplete="off"
            placeholder="验证码"
          ></el-input>
        </el-form-item>
        <!-- `checked` 为 true 或 false -->
        <el-checkbox v-model="checked" @change="remember"
          >记住密码</el-checkbox
        >
        <el-button class="wf-forgot-pass" type="text" @click="open"
          >忘记密码 ？</el-button
        >
        <el-form-item>
          <el-button
            type="primary"
            class="wf-login-btn"
            @click="submitForm('ruleForm')"
            :disabled="isLoginBtn"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { mapActions } from "vuex";
// import {VerificatApi} from "../http/userApi"

export default {
  data() {
    var checkName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    var validateTel = (rule, value, callback) => {
      if (value === "") {
        (this.isTelBtn = true), callback(new Error("请输入手机号"));
      } else if (
        !/^(((13[0-9])|(14[5-7])|(15[0-9])|(17[0-9])|(18[0-9]))+\d{8})$/.test(
          value
        )
      ) {
        (this.isTelBtn = false), callback(new Error("请输入正确的手机号"));
      } else {
        (this.isTelBtn = false), callback();
      }
    };
    var validatemessage = (rule, value, callback) => {
      if (value === "") {
        (this.isLoginBtn = true), callback(new Error("请输入验证码"));
      } else {
        (this.isLoginBtn = false), callback();
      }
    };
    return {
      checked: false,
      isLoginBtn: true,
      isTelBtn: true,
      isObtain: true,
      timeLeft: 10,
      ruleForm: {
        userpass: "",
        username: "",
        phone: "",
        message: "",
      },
      rules: {
        userpass: [{ validator: validatePass, trigger: "blur" }],
        username: [{ validator: checkName, trigger: "blur" }],
        phone: [{ validator: validateTel, trigger: "blur" }],
        message: [{ validator: validatemessage, trigger: "blur" }],
      },
    };
  },
  created() {
    console.log(this.checked);
  },
  methods: {
    //引入loginAction
    ...mapActions(["userStore/loginAction", "userStore/authorityAction"]),
    getVerificatCode() {
      this.isTelBtn = true;
      this.isObtain = false;
      let time = setInterval(() => {
        this.timeLeft--;
        if (this.timeLeft == 0) {
          clearInterval(time);
          this.timeLeft = 10;
          this.isObtain = true;
          this.isTelBtn = false;
        }
      }, 1000);
      //获取验证码
      this.$http({
        url: "/msg/sendPhoneCode",
        method: "GET",
        params: {
          phone: this.ruleForm.phone,
        },
      })
        .then((res) => {
          console.log(res.data);
          if (res.data.code == 0) {
            this.$message({
              message: "短信验证码发送失败",
            });
          } else {
            this.$message({
              message: "短信验证码发送成功",
              type: "success",
            });
          }
        })
        .catch(() => {
          this.$message({
            message: "短信验证码发送失败",
          });
        });
    },
    remember() {
      // this.checked = !checked;
      // console.log(checked);
      // console.log(this.checked);
      if (this.checked) {
        console.log('记住密码');
        localStorage.setItem("rememberName", this.ruleForm.username);
        localStorage.setItem("rememberPass", this.ruleForm.userpass);
        localStorage.setItem("rememberPhone", this.ruleForm.phone);
      } else {
        localStorage.setItem("rememberName", "");
        localStorage.setItem("rememberPass", "");
        localStorage.setItem("rememberPhone", "");
      }
    },
    inputName(name) {
      console.log(name);
      if (name == localStorage.getItem("rememberName")) {
        this.ruleForm.userpass = localStorage.getItem("rememberPass");
        this.ruleForm.phone = localStorage.getItem("rememberPhone");
        console.log("jizhumima");
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(
            // this.ruleForm.message,
            this.ruleForm.phone,
            this.ruleForm.userpass,
            this.ruleForm.username
          );
          this.$http({
            url: "/admin/login",
            method: "POST",
            params: {
              phone: this.ruleForm.phone,
              password: this.ruleForm.userpass,
              username: this.ruleForm.username,
              // message: this.ruleForm.message,
            },
          })
            .then((res) => {
              if (res.data.code == 1) {
                // console.log("登录成功", res);
                this["userStore/loginAction"]({
                  phone: this.ruleForm.phone,
                  // message: this.ruleForm.message,
                  username: this.ruleForm.username,
                  token: res.data.token,
                });
                //获取权限
                // console.log('获取权限');
                this.$http({
                  url: "/admin/tree",
                  method: "POST",
                  params: {
                    phone: this.ruleForm.phone,
                  },
                })
                  .then((res) => {
                    this["userStore/authorityAction"]({
                      authority: res.data.data,
                    });
                    this.$message({
                      message: "登录成功",
                      type: "success",
                    });
                    // console.log(
                    //   "权限获取成功",
                    //   JSON.parse(localStorage.getItem("routes"))
                    // );

                    this.$router.push("/");
                  })
                  .catch((err) => {
                    this.$message("权限获取失败");
                    console.log("权限获取失败", err);
                  });
              } else {
                this.$message("账号或密码错误");
                console.log("账号或密码错误", res);
              }
            })
            .catch((err) => {
              this.$message("登录失败");
              console.log("登录失败", err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    open() {
      this.$prompt("请输入您的电子邮箱来重置密码", "忘记密码", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern:
          /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
        inputErrorMessage: "邮箱格式不正确",
      })
        .then(({ value }) => {
          this.$message({
            type: "success",
            message: "你的邮箱是: " + value,
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.wf-login {
  width: 400px;
  height: 460px;
  box-shadow: 0 0 3px;
  margin: 100px auto;
  box-sizing: border-box;

  .wf-login-text {
    width: 100%;
    height: 60px;
    background-color: #ccc;
    line-height: 60px;
    text-align: center;
    font-size: 26px;
  }
  .wf-login-from {
    margin-top: 40px;
    padding: 0 20px;

    .wf-phone {
      width: 220px;
    }
    .wf-obtain {
      float: right;
      width: 120px;
    }

    .wf-forgot-pass {
      float: right;
      padding: 0;
    }
    .wf-login-btn {
      margin-top: 20px;
      width: 100%;
    }
  }
}
</style>